package com.itheima.recommend.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

// 同步推荐动态的任务类
@Component
public class MovementScoreJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    // 间隔30秒
    // @Scheduled(cron = "0/30 * * * * ?")
    public void reidsToMongo() {
        System.out.println("动态推荐start................");
        // 1.获取所有推荐动态的key
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                // 2.获取userId
                Long userId = Long.parseLong(key.replace("QUANZI_PUBLISH_RECOMMEND_", ""));
                // 3.获取pid
                String pids = stringRedisTemplate.opsForValue().get(key);
                // 4.清除旧数据
                mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)), RecommendMovement.class);
                // stringRedisTemplate.delete(key);
                // 5.保存推荐动态
                // 5.1 pid字符串切割
                String[] split = pids.split(",");
                // 5.2 遍历
                if (ArrayUtil.isNotEmpty(split)) {
                    for (String pid : split) {
                        // 5.3 创建推荐动态对象
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(System.currentTimeMillis());// 推荐时间
                        recommendMovement.setUserId(userId); // 用户id
                        recommendMovement.setPid(Long.parseLong(pid)); // 大数据id
                        // 查询动态详情
                        Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);
                        recommendMovement.setPublishId(movement.getId()); // 动态id
                        recommendMovement.setScore(RandomUtil.randomDouble(60, 99)); // 推荐得分

                        // 5.4 保存
                        mongoTemplate.save(recommendMovement);
                    }
                }

            }
        }
        System.out.println("动态推荐end................");
    }
}
